#!/bin/bash

gpio_group=(424 421 435 480 433 484 430 485 419 431 422 432 425 426 434 482 429)
toggle_pins()
{
    for((i=0;i<${#gpio_group[*]};i++))
    do
#           echo ${gpio_group[i]}
            ./gpio set ${gpio_group[i]}
#            sleep $sleepTime
    done

    for((i=0;i<${#gpio_group[*]};i++))
    do
            ./gpio clear ${gpio_group[i]}
#            sleep $sleepTime
    done
}


STANDARD_VALUES=(953 1900 2844 953 1900 2844 592) #adc channel 0-6 standard value
result=(1 1 1 1 1 1 1 1) #1:fail, 0:pass,adc0,1,2,3,4,5,6,gpio_pair
lev_low=9
lev_up=11
lev=10

readings=($(cat /sys/bus/iio/devices/iio:device0/in_voltage0_raw  &&\
            cat /sys/bus/iio/devices/iio:device0/in_voltage1_raw  &&\
            cat /sys/bus/iio/devices/iio:device0/in_voltage2_raw  &&\
            cat /sys/bus/iio/devices/iio:device0/in_voltage3_raw  &&\
            cat /sys/bus/iio/devices/iio:device0/in_voltage4_raw  &&\
	    cat /sys/bus/iio/devices/iio:device0/in_voltage5_raw  &&\
            cat /sys/bus/iio/devices/iio:device0/in_voltage6_raw))


echo ${readings[0]},${readings[1]},${readings[2]},${readings[3]},${readings[4]},${readings[5]},${readings[6]},

for i in {0..6}; 
do
  # lower_limit=$(echo "${STANDARD_VALUES[$i]} * 0.9" /1 | bc)
  # upper_limit=$(echo "${STANDARD_VALUES[$i]} * 1.1" /1 | bc)
  lower_limit=$(echo "${STANDARD_VALUES[$i]} * 9" /10 )
  upper_limit=$(echo "${STANDARD_VALUES[$i]} * 11" /10 )



  if [[ ${readings[$i]} -lt $lower_limit || ${readings[$i]} -gt $upper_limit ]]; then
    echo "FAIL: Channel $i ADC value (${readings[$i]}) is outside of the standard range (${lower_limit}-${upper_limit})"
    result[i]=1
  else
    result[i]=0
  fi
done

#echo ${result[0]},${result[1]},${result[2]},${result[3]},${result[4]},${result[5]},${result[6]},

#--------------------------------------------------------------------#

#./gpio input 425
sleepTime=0.1
toggle_pins
sleep 1
#./gpio input 425
p9_status=$(./gpio input 425)
[ $p9_status -eq 1 ] && { result[7]=0; echo "Header P9 GPIO Test PASS"; }


#--------------------------------------------------------------------#

sum=0
for i in "${result[@]}"
do
	sum=$((sum + i))
done
echo "sum=" $sum
[ $sum -ge 1 ] && { echo "Header P9 Test FAIL"; exit 2; }

./gpio clear 491
echo "Header P9 ALL Test PASS"
exit 0
